package cn.hrc.controller;

import cn.hrc.dao.FileDao;
import cn.hrc.dao.UserDao;
import cn.hrc.entity.LargeFile;
import cn.hrc.entity.User;
import cn.hrc.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/adm/tea")
public class AdmTeaController {
    @Autowired
    UserDao userDao;
    @Autowired
    FileDao fileDao;
    @GetMapping("/delete/{go2uid}")
    public String deleteTea(@PathVariable("go2uid")Integer uid){
        /** 先用uid要删除的对象并返回 */
        User teacher = userDao.findByUid(uid);
        /** 用返回的对象的pic先删除图片 */
        fileDao.delete(teacher.getPic());
        /** 删除图片，删除对象 */
        int sql = userDao.deleteTea(uid);
        System.out.println("删除成功");
        return "forward:/adm/tea/show";
    }
    @GetMapping("/go2update/{delByUid}")
    public String go2UpdateTea(@PathVariable("delByUid") Integer uid, Model model, HttpSession session){
        System.out.println("去更改功能\tUid:\t"+uid);
        User who = (User)session.getAttribute("who");
        if(who == null){
            model.addAttribute("loginmsg","请先登录在调用该功能");
            //redirect:
            return "/login";
        }
        /** 传递修改查询条件给show【数据太长传不过去直接传udi】 */
        return "forward:/adm/tea/show?delByUid="+uid;
    }
    @PostMapping("/update")
    public String UpdateTea(User user, MultipartFile file, Model model, HttpSession session){
        System.out.println("user:\t"+user);
        User who = (User)session.getAttribute("who");
        if(who == null){
            model.addAttribute("loginmsg","请先登录在调用该功能");
            //redirect:
            return "/login";
        }
        /** 判断图片是否要更换 */
        if (file == null || file.isEmpty() == true){
            System.out.println("没有上传图片");
        }else {
            try {/** 建一个新对象 要更改的图片id 放进去 */
                LargeFile lf = new LargeFile();
                lf.setId(user.getPic());
                /** 存入图片名称 */
                lf.setFilename(file.getOriginalFilename());
                byte[] buf = file.getBytes();
                System.out.println("length:\t"+buf.length);
                lf.setContent(buf);
                /** 删除原本的图片 ,再用原本的图片ID ,进行添加图片 */
                fileDao.delete(user.getPic());
                fileDao.add(lf);

            } catch (IOException e) {
                System.out.println(e.getMessage());
                model.addAttribute("bcsb","图片更改失败");
            }//try
        }//else
        int sql = userDao.updateUser(user);
        if (sql > 0) {System.out.println("更改成功");}
        return "forward:/adm/tea/show";
    }
    /**
     * RequestParam 参数注解
     * <input name 和 接收变量名不一致时，做转换处理
     * required = true 页面必须有输入，默认值 false */
    @PostMapping("/add")
    public String teaAdd(User user,MultipartFile file,Model model,HttpSession session){
        System.out.println("user：\t"+user+"\t+file：\t"+file);
        User who = (User)session.getAttribute("who");
        if(who == null){
            model.addAttribute("loginmsg","请先登录在调用该功能");
            //redirect:
            return "/login";
        }
        /** 判断是否添加图片没有就返回添加页面【表示添加失败】 */
        if (file == null || file.isEmpty() == true){
            System.out.println("没有上传图片");
            return "forward:/adm/tea/show";
        }
        /** 生成唯一的UUDI  并且去掉【-】 */
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replace("-","");
        try {
            System.out.println("UUID:\t"+uuid);
            /** 保存图片【图片类】 */
            LargeFile lf = new LargeFile();
            lf.setId(uuid);
            /** 图片名 */
            lf.setFilename(file.getOriginalFilename());
            byte[] buf = file.getBytes();
            System.out.println("length:\t"+buf.length);
            lf.setContent(buf);
            fileDao.add(lf);//添加到数据库
        } catch (IOException e) {
            System.out.println(e.getMessage());
            model.addAttribute("bcsb","保存失败");
            return "forward:/adm/tea/show";
        }
        /** 添加教师【教师绑定tea】 */
        user.setRole("tea");
        /** 把 UUID 放到学生对象里 */
        user.setPic(uuid);
        int sql = userDao.addUser(user);
        System.out.println(sql);
        return "forward:/adm/tea/show";
    }
    @RequestMapping("/show")
    public String teaShow(HttpSession session, Model model, Integer delByUid){
        System.out.println("tea:\t"+delByUid);
        User who = (User)session.getAttribute("who");
        if(who == null){
            model.addAttribute("loginmsg","请先登录在调用该功能");
            //redirect:
            return "/login";
        }
        /** 查询教师集合*/
        List<UserInfo> userList = userDao.findByRole("tea");
        //更改用的
        User teacher;
        //平常保持为添加功能
        if (delByUid == null){
            teacher = new User();//没用更改是空的，给他个【地址】
            model.addAttribute("function","教师添加");
            model.addAttribute("method","add");
        }else {
            //不为空，查询要更改的对象
            teacher = userDao.findByUid(delByUid);
            model.addAttribute("function","教师更改");
            model.addAttribute("method","update");
        }
        model.addAttribute("teacher",teacher);
        model.addAttribute("users",userList);
        return "adm/teaShow";
    }
}
